<template>
    <div class="headerBox">
        <div class="header_textarea_box">
            <el-button size="mini" class="formatBotton" @click="formatJson">Format</el-button>
            <el-button size="mini" class="getJsonBotton" @click="formatUrl">从URL中获取</el-button>
            <textarea ref="header"></textarea>
        </div>
        <quickInsert :editor="editor"></quickInsert>
    </div>
</template>
<script>
    import { mapState } from 'vuex';

    import quickInsert from './quickInsert';


    let CodeMirror = require("codemirror/lib/codemirror");
    import "codemirror/lib/codemirror.css";
    import "codemirror/theme/mdn-like.css";
    import "codemirror/mode/javascript/javascript.js";
    import "codemirror/addon/fold/foldgutter.css";
    import "codemirror/addon/fold/foldcode.js";
    import "codemirror/addon/fold/foldgutter.js";
    import "codemirror/addon/fold/brace-fold.js";
    import "codemirror/addon/fold/comment-fold.js";
    import "codemirror/addon/edit/matchbrackets";
    import 'codemirror/addon/hint/javascript-hint'
    import 'codemirror/addon/hint/show-hint'
    import 'codemirror/keymap/sublime.js'
    import 'codemirror/keymap/emacs.js'
    import 'codemirror/keymap/vim.js'

    export default {
        props: ['height', 'rest', 'url', 'ChangeValue'],
        components: {
            quickInsert
        },
        data() {
            return {
                editor: null,
            }
        },
        mounted() {
            this.editor = CodeMirror.fromTextArea(this.$refs.header, {
                mode: 'text/javascript',
                indentWithTabs: true,
                smartIndent: false,
                lineNumbers: true,
                lineWrapping: true,
                foldGutter: true,
                matchBrackets: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                theme: 'mdn-like',
            });
            this.editor.on('beforeChange', (instance, changeObj) => {
                // console.log(this.editor.getSelection());
                if (changeObj.origin == '+input' && (changeObj.text == '\'' || changeObj.text == '\"')) {
                    var _str = this.editor.getSelection();
                    if (_str.toString().length > 0) {
                        this.editor.replaceSelection(_str + _str + changeObj.text);
                    };
                    console.log(true);
                };
            });
            this.editor.on('change', () => {
                // this.header = this.editor.getValue();
                this.ChangeValue('rest', this.editor.getValue());
            });
        },
        methods: {
            refreshEditor() {
                this.editor.refresh();
            },
            formatJson() {
                var str = this.editor.getValue();
                str = this.beautify(str);
                this.editor.setValue(str);
            },
            beautify(source) {
                function looks_like_html(source) {
                    var trimmed = source.replace(/^[ \t\n\r]+/, '');
                    return trimmed && (trimmed.substring(0, 1) === '<');
                };
                var output,
                    opts = {
                        // brace_style : "expand"
                    };
                opts.indent_char = ' ';
                opts.preserve_newlines = "-1";
                if (looks_like_html(source)) {
                    output = html_beautify(source, opts);
                } else {
                    output = js_beautify(source, opts);
                };
                return output;
            },
            formatUrl() {
                var string = this.url;
                var urlArray = string.split('/');
                var _value = this.editor.getValue();
                var _Object = '';
                try {
                    if (_value) {
                        _Object = eval('_Object =' + this.editor.getValue());
                    } else {
                        _Object = {};
                    };
                    for (let i = 0; i < urlArray.length; i++) {
                        const element = urlArray[i];
                        var str = element.match(/(?<={).+(?=})/);
                        if (str && str.length > 0) {
                            _Object[str] = '';
                        } else {
                            var re = element.match(/(?<=:).*/);
                            if (re && re.length > 0) {
                                _Object[re] = '';
                            }
                        };
                    };
                    if (JSON.stringify(_Object) != '{}') {
                        this.editor.setValue(this.beautify(JSON.stringify(_Object)));
                        this.ChangeValue('rest', this.editor.getValue());
                    };
                } catch (error) {
                    this.$message({
                        dangerouslyUseHTMLString: true,
                        message: '<span>Rest参数格式化错误</span><br><span class="delete">' + error + '</span>',
                        type: 'warning'
                    });
                };
            },
        },
    }

</script>
<style>
    .headerBox .getJsonBotton {
        position: absolute;
        top: 40px;
        right: 4px;
        z-index: 10;
    }
</style>